<template>
    <div style="width: 100%">
        <h1>学生管理</h1>

        <el-dialog :title="headerTitle"  :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules"  ref="form">

                <el-row>
                    <el-col :span="20" :offset="2">
                        <el-form-item label="姓名:" label-width="90" prop="name">
                            <el-input v-model="form.name" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :offset="2" >
                        <el-form-item label="电话:" label-width="90" prop="phone">
                            <el-input v-model="form.phone" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :offset="2">
                        <el-form-item label="身份证：" label-width="90" prop="identity">
                            <el-input v-model="form.identity" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8" :offset="2">
                        <el-form-item label="性别：" v-model="form.sex">
                            <el-radio v-model="form.sex" label="男">男</el-radio>
                            <el-radio v-model="form.sex" label="女">女</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10" :offset="2">
                        <el-form-item label="班级：" prop="classesId">
                            <el-select v-model="form.classesId"  filterable clearable placeholder="请选择班级">
                                <el-option
                                        v-for="item in classesList"
                                        :key="item.id"
                                        :label="item.classesName"
                                        :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="18" :offset="2">
                        <el-form-item label="学生状态：" >
                            <el-radio v-model="form.state" :label="0">正常</el-radio>
                            <el-radio v-model="form.state" :label="1">毕业</el-radio>
                            <el-radio v-model="form.state" :label="2">休学</el-radio>
                            <el-radio v-model="form.state" :label="3">退学</el-radio>
                            <el-radio v-model="form.state" :label="4">开除</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :offset="2">
                        <el-form-item label="学生状态情况:" label-width="90">
                            <el-input
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入内容"
                                    v-model="form.info">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleReset">重置</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handlerAddStudent">确 定</el-button>
            </div>

        </el-dialog>

        <!--导入excel-->
        <el-dialog
                title="导入"
                :visible.sync="excelUpOpen"
                width="80%"
                >

            <div class="excel-wrapper" style="width: 90%">

                <el-row>
                    <el-col :span="3" :offset="3">
                        <el-button type="primary">
                            <el-link href="https://wanmacc.oss-cn-hongkong.aliyuncs.com/%E6%A8%A1%E6%9D%BF.xlsx">下载模板</el-link>
                        </el-button>
                    </el-col>


                    <el-col :span="5" >
                        <!-- 上传按钮 -->
                        <input class="input-file"
                               type="file"
                               @change="exportData"
                               style="display:none"
                               accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
                        <el-button type="success"
                                   size="small"
                                   @click="btnClick">上传excel</el-button>
                    </el-col>

                    <el-col :span="10">
                        <span>请选择添加到的班级：</span>
                        <el-select v-model="excelUpVule" filterable placeholder="请选择班级">
                            <el-option
                                    v-for="item in classesList"
                                    :key="item.id"
                                    :label="item.classesName"
                                    :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-col>

                    <el-col :span="2" :offset="1">
                        <el-button type="primary" @click="emptyUpStudent">清空</el-button>
                    </el-col>


                </el-row>

                <!-- END -->

                <!-- 表格 -->
                <el-table :data="tableData"
                          style="width: 100%"
                          height="450"
                          size="mini" >
                    <el-table-column :prop="item"
                                     :label="item"
                                     width="150"
                                     v-for="(item,index) in checkboxTableColumn"
                                     :key="'column'+index">

                    </el-table-column>
                </el-table>
                <!-- END -->

                <!-- 分页 -->
                <el-pagination v-if="excelData != 0"
                               @size-change="handleSizeChange"
                               @current-change="CurrentChange"
                               :current-page="currentPage"
                               :page-sizes="[10, 20, 30,40,50,100,200,500]"
                               :page-size="pageSize"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="total">
                </el-pagination>
                <!-- END -->

            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="excelUpOpen = false">取 消</el-button>
                <el-button type="primary" @click="handleUpStudents">提交</el-button>
            </span>
        </el-dialog>



        <!--导出excel-->
        <el-dialog
                title="导出"
                :visible.sync="excelDlOpen"
                width="30%"
                >
                <label>请选择班级: </label>

                <el-select v-model="excelVule" filterable multiple clearable placeholder="请选择班级">
                    <el-option
                            v-for="item in classesList"
                            :key="item.id"
                            :label="item.classesName"
                            :value="item.id"
                    >
                    </el-option>
                </el-select>

            <span slot="footer" class="dialog-footer">
                <el-button @click="excelDlOpen = false">取 消</el-button>
                <el-button type="primary" @click="handledownloadExcel">确 定</el-button>
            </span>
        </el-dialog>





            <!--学生列表-->
        <el-row :gutter="20">
            <el-col :span="3"><el-button type="primary" @click="handlerAddEstimate">添加</el-button></el-col>
            <el-col :span="1"  ><el-button type="danger" icon="el-icon-delete" @click="handleMultipleDelete">批量删除</el-button></el-col>

            <el-col :span="1" :offset="2"   ><el-button type="primary" @click="excelUpOpen = true">导入excel<i class="el-icon-upload el-icon--right"></i></el-button></el-col>
            <el-col :span="1" :offset="2" ><el-button type="primary"  @click="excelDlOpen = true">导出excel</el-button></el-col>

            <el-col :span="3" :offset="2">

                <el-select v-model="student.sex"  placeholder="请选择性别">
                    <el-option label="全部" value="全部"></el-option>
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                </el-select>
            </el-col>

            <el-col :span="3">
                <el-select v-model="student.classesId"  filterable clearable placeholder="请选择班级">
                    <el-option
                            v-for="item in classesList"
                            :key="item.id"
                            :label="item.classesName"
                            :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-col>


            <el-col :span="3">
                <el-input
                    placeholder="请输入姓名"
                    v-model="student.name"
                    clearable
                >
                </el-input>
            </el-col>

            <el-col :span="1"><el-button type="primary" plain @click="handleStudentList">搜索</el-button></el-col>
        </el-row>



<!--        列表-->
        <el-table
                v-loading="loading"
                ref="multipleTable"
                :data="studentList"
                tooltip-effect="dark"
                style="width: 90%;margin: 0 auto"
                @selection-change="handleSelectionChange">

            <el-table-column
                    type="selection"
                    min-width="5%">
            </el-table-column>

            <el-table-column
                    label="姓名"
                    prop="name"
                    min-width="5%"
            >

            </el-table-column>

            <el-table-column
                    prop="sex"
                    label="性别"
                    min-width="5%">
            </el-table-column>
            <el-table-column
                prop="classes.classesName"
                label="班级"
                min-width="5%"
            >
            </el-table-column>
            <el-table-column
                    prop="phone"
                    label="电话"
                    min-width="5%"
            >
            </el-table-column>
            <el-table-column
                label="注册时间"
                sortable
                min-width="5%"
                prop="classes.inputTime"
            >
                <template slot-scope="scope">
                    <span>{{scope.row.inputTime.toLocaleString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')}}</span>
                </template>
            </el-table-column>

            <el-table-column
                    label="学生状态"
                    min-width="5%"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.state == 0">正常</span>
                    <span v-if="scope.row.state == 1">毕业</span>
                    <span v-if="scope.row.state == 2">休学</span>
                    <span v-if="scope.row.state == 3">退学</span>
                    <span v-if="scope.row.state == 4">开除</span>
                </template>
            </el-table-column>

            <el-table-column
                label="操作"
                min-width="5%"
            >
                <template slot-scope="scope">

                    <el-tooltip content="编辑" placement="top">
                        <el-button
                                type="primary"
                                size="mini"
                                icon="el-icon-edit"
                                @click="handlerChange(scope.$index,scope.row)"
                        >编辑</el-button>
                    </el-tooltip>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

<!--        分页-->
        <el-pagination
                background
                layout="prev, pager, next"
                :current-page="pageNum"
                :page-size="pageInfo.pageSize"
                :total="pageInfo.total"
                :hide-on-single-page="true"
                @current-change="handleStudentList"
        >
        </el-pagination>

    </div>

</template>

<script>
    import * as XLSX from 'xlsx'
    export default {
        data() {

            //验证身份证号
            let checkRegNo = (rule,value,callback) => {
                var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
                var tip = "";
                var pass= true;
                var patt1=new RegExp("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)");
                if(value == ''){
                    pass = true;
                }else if(!patt1.test(value)){
                    callback(new Error("身份证号格式错误"));
                    pass = false;
                } else if(!city[value.substr(0,2)]){
                    callback(new Error("地址编码错误"));
                    pass = false;
                }else{
                    //18位身份证需要验证最后一位校验位
                    if(value.length == 18){
                        value = value.split('');
                        //∑(ai×Wi)(mod 11)
                        //加权因子
                        var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                        //校验位
                        var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                        var sum = 0;
                        var ai = 0;
                        var wi = 0;
                        for (var i = 0; i < 17; i++)
                        {
                            ai = value[i];
                            wi = factor[i];
                            sum += ai * wi;
                        }
                        var last = parity[sum % 11];
                        if(parity[sum % 11] != value[17]){
                            callback(new Error("身份证号码错误"));
                            pass =false;
                        }



                    }
                }
                if(pass){
                    //判断
                    if(!this.form.id){
                        var str = "";
                        for(var i=0;i<value.length;i++){
                            str+= value[i]
                        }
                        this.$axios.post("/student/identityRepeat",str,{headers:{'Content-Type': 'application/json'}}).then(response=>{
                            console.log(response.data.code==10001)
                            if(response.data.code==10001){
                                callback(new Error("身份证号码已存在"));
                                pass =false;
                            }
                        })
                    }
                    else {
                        callback();
                    }

                }
            }

            return {
                form: {
                    sex:'男',
                    state:0,
                },
                rules:{
                    name:[
                        { required: true, message: '请输入姓名', trigger: 'blur' },
                    ],
                    phone: [
                        { required: true, message: '手机号不能为空' },
                        { type: 'number',
                            message: '手机号格式不正确',
                            trigger: 'blur',
                            transform (value) {
                                var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/
                                if (!phonereg.test(value)) {
                                    return false
                                }else{
                                    return Number(value)
                                }
                            }
                        }
                    ],
                    identity:[
                        { required: true, message: '身份证不能为空' },
                        { validator: checkRegNo, trigger: 'blur' }

                    ]
                },
                pageNum:1,
                student: {sex:"全部"},
                pageInfo: [],
                studentList: [],
                multipleSelection: [],
                input:'',
                classesList: [],
                dialogFormVisible : false,
                loading: true,
                headerTitle:'',
                //excel上传窗口
                excelUpOpen:false,
                //excel导出窗口
                excelDlOpen:false,

                excelVule:[],
                excelUpVule:undefined,

                //所有键的值
                columnHeader: [],

                // 导入的excel的数据
                excelData: [],

                // 表格显示列
                checkboxTableColumn: [],

                //表格数据
                tableData: [],

                // 当前分页
                currentPage: 1,

                // 每页显示数量
                pageSize: 10,

                // 数据总数
                total: 0,

                //excel中的学生
                upStudents:[],
            }

        },
        created() {
            this.handleStudentList()

        },
        methods: {
            //列表 条件查询
            handleStudentList(pageNum) {
                this.loading = true;
                if (typeof pageNum == "number") {
                    this.pageNum = pageNum;
                } else {
                    this.pageNum = 1;
                }

                // console.log(this.student)
                this.$axios.post("/student/list", this.student, {params: {pageNum: this.pageNum}}).then(response => {
                    this.pageInfo = response.data.studentList;
                    this.studentList = response.data.studentList.list;
                    this.classesList = response.data.classesList;
                    this.loading = false;
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //重置
            handleReset() {
                this.form = {
                    sex: '男',
                    state: 0,
                };
            },
            //添加如果存在修改的id清空
            handlerAddEstimate(){
                this.headerTitle="添加学生";
              if(this.form.id!=null){
                  this.form = {
                      sex: '男',
                      state: 0,
                  };
              }
                this.dialogFormVisible = true;
            },
            //添加
            handlerAddStudent() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        this.dialogFormVisible = false;
                        this.$axios.post("/student/save", this.form).then(response => {
                            if (response.code != 10001) {
                                this.handleStudentList();
                                this.form = {
                                    sex: '男',
                                    state: 0,
                                };
                            }

                        })
                    }

                });
            },
            //修改
            handlerChange(index, row) {

                this.$axios.post("/student/findById/" + row.id).then(response => {
                    this.form = response.data.student;
                    this.headerTitle="修改学生";
                    this.dialogFormVisible = true;
                })

            },
            //单个删除
            handleDelete(row){
                this.$confirm('确认删除该学生, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.get("/student/delete/"+row.id).then(response=>{
                        this.handleStudentList();
                    })
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
        //    批量删除
            handleMultipleDelete(){
                this.$confirm('确认删除这些学生, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var idList = [];
                    for (var i=0;i < this.multipleSelection.length;i++ ){
                        idList.push(this.multipleSelection[i].id);
                    }
                    this.$axios.post("/student/multipleDelete",idList).then(response=>{
                        if(response.data.code==10001){
                            return;
                        }
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        //刷新
                        this.handleStudentList();
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //导入excel按钮
            handleImportExcel(){


                this.excelUpOpen = false;
            },
            //导出excel按钮
            handledownloadExcel(){
                console.log(this.excelVule)
                // window.open("http://localhost:8080/student/export")

                this.$axios.post("/student/export",this.excelVule,{responseType:'blob'}).then(res => {
                    console.log(res)
                    const link = document.createElement('a')
                    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
                    link.style.display = 'none'
                    link.href = URL.createObjectURL(blob)
                    link.setAttribute('download', `学生.xlsx`)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    this.excelDlOpen = false;
                })
            },


            // 将上传input框点击事件改为按钮
            btnClick() {
                document.querySelector('.input-file').click()
            },

            // 解析excel
            exportData(event) {
                if (!event.currentTarget.files.length) {
                    return
                }
                const that = this
                // 拿取文件对象
                let f = event.currentTarget.files[0]
                //这里已经拿到了excel的file文件，若是项目需求，可直接$emit丢出文件
                // that.$emit('getMyExcelData',f);
                // 用FileReader来读取
                let reader = new FileReader()
                // 重写FileReader上的readAsBinaryString方法
                // FileReader.prototype.readAsBinaryString = function(f) {
                //   let binary = "";
                //   let wb; // 读取完成的数据
                //   let outdata; // 你需要的数据
                //   let reader = new FileReader();
                reader.onload = function (e) {
                    // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
                    // let bytes = new Uint8Array(reader.result);
                    // let length = bytes.byteLength;
                    // for (let i = 0; i < length; i++) {
                    //   binary += String.fromCharCode(bytes[i]);
                    // }
                    var data = e.target.result
                    // 接下来就是xlsx
                    var wb = XLSX.read(data, {
                        type: 'buffer',
                    })
                    var outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
                    // 导出格式为json，{表数据：[]}
                    // console.log(outdata)
                    that.excelData = outdata
                    that.tableData = outdata.slice(0, 10)
                    that.total = outdata.length
                    // console.log(that.tableData[0])

                    // 获取数据的key
                    var importDataThead = Array.from(Object.keys(outdata[0])).map(
                        (item) => {
                            return item
                        }
                    )

                    that.columnHeader = importDataThead
                    that.checkboxTableColumn = importDataThead.slice(0, 9)
                    var as = that.checkboxTableColumn[0];
                    // console.log(as)
                    //不能直接取值 需要加上[]
                    // console.log(that.tableData[3][as])

                    //定义了一个数组存放导入的学生
                    let upStudent=[];


                    Array.from(that.tableData,(item)=>{
                        let newStudent = {
                            name:'',
                            sex:'',
                            identity:'',
                            phone:'',
                            classesId:''
                        }
                        Array.from(that.checkboxTableColumn,(key)=>{
                            newStudent[key] = item[key];
                        })
                        upStudent.push(newStudent);
                    })
                    // console.log(upStudent)
                    that.upStudents = upStudent;
                    // console.log(that.tableData)
                    // console.log(importDataThead)
                }
                reader.readAsArrayBuffer(f)
                // };
                // reader.readAsBinaryString(f);
            },

            // 分页切换
            CurrentChange(val) {
                this.currentPage = val

                this.tableData = this.excelData.slice(
                    (val - 1) * this.pageSize,
                    val * this.pageSize - 1
                )
            },
            // 每页显示数量改变
            handleSizeChange(val) {
                this.pageSize = val
                this.tableData = this.excelData.slice(
                    (this.currentPage - 1) * val,
                    this.currentPage * val - 1
                )
            },

            //提交学生
            handleUpStudents(){
                if(this.tableData.length==0){
                    this.$message.error('请上传excel！！！！！！');
                }
                else if(this.excelUpVule===undefined){
                    this.$message.error('请选择班级！！！！！！');
                    return;
                }


                let that = this;
                // console.log(this.excelUpVule)
                //数据库已经有的
                let repeatStudent = [];
                //身份证不对
                let errorStudent = [];
                //数据库没有的
                let submit = [];
                //同步
                let asyn = [];

                //判断学生是否重复或者身份证正确
                this.upStudents.forEach((item,i) => {
                    let flag = this.validID(item.identity);
                    if(flag){
                        // submit.push(this.isStudentId(item))
                        var is;
                        asyn.push(this.isStudentId(item).then( result => {
                            is = result
                            console.log(result)
                            if(is){
                                item.classesId=this.excelUpVule
                                submit.push(item)
                            }else {
                                repeatStudent.push(item.name)
                            }
                        }))
                    }else {
                        errorStudent.push(item.name)
                    }
                })
                //保证axios同步执行
                Promise.all(asyn).then( ()=>{

                    if(repeatStudent.length>0){

                        this.$message({
                            message: '有重复的学生:'+ repeatStudent.toString(),
                            type: 'warning'
                        });

                    }

                    setTimeout(function() {
                        if(errorStudent.length>0){
                            that.$message({
                                message: '存在身份证格式错误的学生:'+ errorStudent.toString(),
                                type: 'warning'
                            });
                        }
                    }, 1000)


                    if(submit.length>0){
                        this.$axios.post("/student/ExcelAdd",submit).then(res => {
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                            this.excelUpOpen = false
                            this.emptyUpStudent();
                        })
                    }


                })
            },

            //判断数据身份证
            isStudentId(item){
                return new Promise(((resolve, reject) => {
                    this.$axios.post("/student/identityRepeat",item.identity,{headers:{'Content-Type': 'application/json'}}).then(response=>{
                        // console.log(response.data.code==10001)
                        if(response.data.code==10001){
                            // repeatStudent.push(item.name);
                            // console.log(repeatStudent)
                            resolve(false);
                        }else {
                            resolve(true);
                        }
                    })
                }))


            },
            //验证身份证
            validID(value) {
                // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
                let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
                if(value == '') {
                    return false;
                } else if (reg.test(value)) {
                    return true;
                } else {
                    return false;
                }
            },

            //清空上传
            emptyUpStudent(){
                this.tableData = [];
                this.excelData = [];
                this.upStudents = [];
            }

        }
    }
</script>

<style scoped>
/*<!--上传样式-->*/
    .excel-wrapper {
        /* height: 100vh; */
        /* width: 600px; */
        overflow: scroll;
        background: rgb(226, 226, 226);
        padding: 20px;
    }
</style>